import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'

// 后续页面组件可根据需要添加
// import UserList from '../views/UserList.vue'
// import OrderList from '../views/OrderList.vue'
// import ProductList from '../views/ProductList.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard
  }
  // 后续管理端页面可在此添加
  // {
  //   path: '/admin',
  //   component: AdminLayout,
  //   children: [
  //     { path: 'users', component: UserList },
  //     { path: 'orders', component: OrderList },
  //     { path: 'products', component: ProductList }
  //   ]
  // }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由拦截：未登录跳转到 /login
router.beforeEach(async (to, from, next) => {
  // 允许直接访问登录页
  if (to.path === '/login') {
    // 如果已经登录，跳转到首页
    const token = localStorage.getItem('token')
    if (token) {
      try {
        // 验证token是否有效
        const response = await fetch('/api/validate-token', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        })
        if (response.ok) {
          return next('/') // token有效，跳转到首页
        }
      } catch (error) {
        // token验证失败，清除本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
      }
    }
    return next()
  }

  // 检查本地是否有登录信息
  const token = localStorage.getItem('token')
  if (!token) {
    return next('/login')
  }

  // 验证token是否有效
  try {
    const response = await fetch('/api/validate-token', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      // token无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      return next('/login')
    }

    next()
  } catch (error) {
    // 网络错误或其他错误，清除本地存储并跳转到登录页
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    return next('/login')
  }
})

export default router 